﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using Redbus.Interfaces;
using SqlSugar;
using System.ComponentModel;
using System.Reflection;
using Warehouse.Services.Repository;
using WCS.Entities;
using WCS.Entities.Api;
using WCS.Entities.Enum;
using WCS.IServices;
using WCS.Services;
using WCS.ViewModels;

namespace WCS.Controllers
{
    /// <summary>
    /// 料口控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TransferPortController : ControllerBase
    {
        #region  Filed

        private readonly ILogger<TransferPortController> _logger;
        private readonly Repository<TransferPort> transferPortRepository;
        private readonly IDeviceManager deviceManager;
        private readonly Mapper mapper;

        /// <summary>
        /// 重构
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="transferPortRepository"></param>
        /// <param name="eventBus"></param>
        /// <param name="deviceManager"></param>
        public TransferPortController(
            ILogger<TransferPortController> logger,
            Repository<TransferPort> transferPortRepository,
           IDeviceManager deviceManager)
        {
            _logger = logger;
            this.transferPortRepository = transferPortRepository;
            this.deviceManager = deviceManager;
        }


        #endregion

        #region 创建

        /// <summary>
        /// 创建对接口
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Create([FromServices] IMapper mapper, PortDto portDto)
        {
            try
            {
                var port = mapper.Map<TransferPort>(portDto);
                if (await transferPortRepository.AddAsync(port))
                {
                    return ApiResultHelp.Success(portDto);
                }
                else
                    return ApiResultHelp.Error("添加失败，服务器发生错误");
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"添加出错!服务器发生错误:{ex.Message}");
            }
        }

        /// <summary>
        /// 导入料口信息
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Import([FromServices] IMapper mapper, PortDto[] tag)
        {

            try
            {
               
                //tag.ForEach(x => x.TaskType = x.Types.Split(',').Select(x => (int)EnumExtension.GetEnumByDescription<TaskType>(x)).ToList());
                var datas = mapper.Map<List<TransferPort>>(tag);


                foreach (var item in datas)
                {
                    if (await transferPortRepository.IsExistAsync(x => x.Id == item.Id))
                    {
                        await transferPortRepository.UpdateAsync(item);
                    }

                    else
                    {
                        await transferPortRepository.AddAsync(item);
                    }
                }
                return ApiResultHelp.Success("导入成功!");
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error("导入失败!" + ex.Message);
            }

        }
        #endregion

        #region 更新


        /// <summary>
        /// 更新对接口信息
        /// </summary>
        /// <param name="id">Port的Id</param>
        /// <param name="port">新的Port信息</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ApiResult> Update([FromServices] IMapper iMapper, string id, PortDto port)
        {
            if (!transferPortRepository.IsExist(x => x.Id == id))
                return ApiResultHelp.Error("没有找到该接口");
            var newport = iMapper.Map<TransferPort>(port);
            if (await transferPortRepository.UpdateAsync(newport))
            {
                return ApiResultHelp.Success(port);
            }
            else
                return ApiResultHelp.Error("修改失败");
        }

        /// <summary>
        /// 启用/禁用料口
        /// </summary>
        /// <param name="id"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        [HttpPatch("{id}/{enable}")]
        public async Task<ActionResult<ApiResult>> Enable(string id, bool enable)
        {
            if (!transferPortRepository.IsExist(x => x.Id == id))
                return ApiResultHelp.Error("没有找到该设备");

            var port = await transferPortRepository.FindAsync(id);
            port.Enable = enable;

            if (await transferPortRepository.UpdateAsync(port))
            {
                return ApiResultHelp.Success(enable);
            }
            else
                return ApiResultHelp.Error("修改失败");
        }
        #endregion

        #region 复位
        /// <summary>
        /// 复位料口
        /// </summary>
        /// <param name="portId">料口Id</param>
        /// <returns></returns>
        [HttpPost("{portId}")]
        public  ActionResult<ApiResult> Reset([FromRoute] string portId)
        {
            var port = deviceManager.Ports.Where(x => x.Id == portId).FirstOrDefault();

            if (port != null)
            {
               
                var result =  port.BelongDevice.Operation.Write(port.AgvAddress, (short)0);

                if (result.IsSucceed)
                    return ApiResultHelp.Success(result);
                else
                    return ApiResultHelp.Error("复位出错");
            }
            else
            {
                return ApiResultHelp.Error("料口不存在!");
            }
        }
        #endregion

        #region 删除

        /// <summary>
        /// 删除对接口
        /// </summary>
        /// <param name="id">对接口Id</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResult>> Delete(string id)
        {

            if (await transferPortRepository.DeleteByIdAsync(id))
            {
                return ApiResultHelp.Success(id);
            }
            else
                return ApiResultHelp.Error("删除失败");
        }

        /// <summary>
        /// 批量删除对接口
        /// </summary>
        /// <param name="ids">要删除的对接口ids</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ActionResult<ApiResult>> DeleteByIds(string[] ids)
        {

            if (await transferPortRepository.DeleteByIdsAsync(ids))
            {
                return ApiResultHelp.Success(ids);
            }
            else
                return ApiResultHelp.Error("删除失败");
        }

        #endregion

        #region 查找

        /// <summary>
        /// 分页查找对接口信息
        /// </summary>
        /// <param name="page">当前页码</param>
        /// <param name="limit">每页大小</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetPortsByPage([FromServices] IMapper iMapper, int page, int limit, [FromQuery] string query)
        {
            RefAsync<int> total = 0;
            try
            {
                if (query != null)
                {
                    JObject jobject = JObject.Parse(query);
                    List<IConditionalModel> models = new List<IConditionalModel>();

                    foreach (var key in jobject.Properties())
                    {
                        if (string.IsNullOrEmpty(key.Value.ToString()))
                            continue;
                        if (key.Name.ToLower() == "content")
                            models.Add(new ConditionalModel()
                            { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Like });
                        else
                            models.Add(new ConditionalModel()
                            { FieldName = key.Name, FieldValue = key.Value.ToString(), ConditionalType = ConditionalType.Like });
                    }
                    var ports = await transferPortRepository.QueryAsync(models, page, limit, total);
                    List<PortDto> portDtos = iMapper.Map<List<PortDto>>(ports);
                    return ApiResultHelp.Success(new { list = portDtos, total = total.Value });
                }
                else
                {
                    var ports = await transferPortRepository.QueryAsync(page, limit, total);
                    List<PortDto> portDtos = iMapper.Map<List<PortDto>>(ports);
                    return ApiResultHelp.Success(new { list = portDtos, total = total.Value });
                }
            }
            catch (Exception ex)
            {
                return ApiResultHelp.Error($"查询出错:{ex.Message}");
            }
        }

        /// <summary>
        /// 是否存在设备
        /// </summary>
        /// <returns></returns>
        [HttpGet()]
        public async Task<ActionResult<ApiResult>> Check([FromQuery] string query)
        {
            JObject jobject = JObject.Parse(query);
            try
            {
                List<IConditionalModel> models = new List<IConditionalModel>();

                foreach (var key in jobject.Properties())
                {
                    if (key.Name.ToString() == "id" && jobject.Count > 1)
                        continue;
                    else
                        models.Add(new ConditionalModel()
                        {
                            FieldName = key.Name,
                            FieldValue = key.Value.ToString(),
                            ConditionalType = ConditionalType.Equal
                        });
                }
                var ports = await transferPortRepository.Context.Queryable<TransferPort>().Where(models).ToListAsync();
                if (jobject.ContainsKey("id") && jobject.Count > 1)
                {
                    var count = ports.Count(x => x.Id != jobject["id"].ToString());
                    return ApiResultHelp.Success(count);
                }
                return ApiResultHelp.Success(ports.Count);
            }
            catch (Exception e)
            {
                return ApiResultHelp.Error("查找料口" + e.Message);
            }
        }

        /// <summary>
        /// 获取所有的对接口信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult GetAll()
        {
            var ports = transferPortRepository.Context.Queryable<TransferPort>().ToDictionary(t => t.Id, t => t.Name);
            return ApiResultHelp.Success(ports);
        }

        /// <summary>
        /// 获取所有的任务类型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> GetTaskTypes()
        {
            Dictionary<string, TaskType> types = new Dictionary<string, TaskType>();
            foreach (TaskType value in Enum.GetValues(typeof(TaskType)))
            {
                var fi = value.GetType().GetField(value.ToString());
                var attributes = fi?.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
                types.Add(attributes?[0].Description, value);
            }
            return ApiResultHelp.Success(types.ToArray());
        }

        #endregion
    }
}
